/**
 * 简单的缓存工具
 * 提供会话存储和本地存储的功能
 */

const cache = {
    session: {
        set: function(key, value) {
            if (this.isSessionStorageAvailable()) {
                window.sessionStorage.setItem(key, value);
            }
        },
        get: function(key) {
            if (this.isSessionStorageAvailable()) {
                return window.sessionStorage.getItem(key);
            }
            return null;
        },
        setJSON: function(key, jsonValue) {
            if (this.isSessionStorageAvailable()) {
                window.sessionStorage.setItem(key, JSON.stringify(jsonValue));
            }
        },
        getJSON: function(key) {
            if (this.isSessionStorageAvailable()) {
                const value = window.sessionStorage.getItem(key);
                if (value) {
                    try {
                        return JSON.parse(value);
                    } catch (e) {
                        return null;
                    }
                }
            }
            return null;
        },
        remove: function(key) {
            if (this.isSessionStorageAvailable()) {
                window.sessionStorage.removeItem(key);
            }
        },
        isSessionStorageAvailable: function() {
            try {
                return window && window.sessionStorage;
            } catch (e) {
                return false;
            }
        }
    },
    local: {
        set: function(key, value) {
            if (this.isLocalStorageAvailable()) {
                window.localStorage.setItem(key, value);
            }
        },
        get: function(key) {
            if (this.isLocalStorageAvailable()) {
                return window.localStorage.getItem(key);
            }
            return null;
        },
        setJSON: function(key, jsonValue) {
            if (this.isLocalStorageAvailable()) {
                window.localStorage.setItem(key, JSON.stringify(jsonValue));
            }
        },
        getJSON: function(key) {
            if (this.isLocalStorageAvailable()) {
                const value = window.localStorage.getItem(key);
                if (value) {
                    try {
                        return JSON.parse(value);
                    } catch (e) {
                        return null;
                    }
                }
            }
            return null;
        },
        remove: function(key) {
            if (this.isLocalStorageAvailable()) {
                window.localStorage.removeItem(key);
            }
        },
        isLocalStorageAvailable: function() {
            try {
                return window && window.localStorage;
            } catch (e) {
                return false;
            }
        }
    }
};

export default cache;